package cn.school.job.hotel;

import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.school.async.AsyncConfig;
import cn.school.attendance.dormitory.dao.DormitoryAttendanceMapper;
import cn.school.attendance.dormitory.vo.StudentAttendanceVO;
import cn.school.common.utils.SysUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: tzw
 * @date: 2024/3/20 16:18
 * @description: 自动推送未归寝学生信息到对应班主任
 */
@Slf4j
public class SendMessageToTeacherJob extends QuartzJobBean {
    @Resource
    private DormitoryAttendanceMapper dormitoryAttendanceMapper;
    @Resource
    private AsyncConfig asyncConfig;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String nowDate = now.format(formatter);
        String tenantId = "1";
        //缺寝学生名单
        List<StudentAttendanceVO> absenceStudentAndTeacherOpenIdList = dormitoryAttendanceMapper.getAbsenceStudentAndTeacherOpenIdList(nowDate, tenantId);
        //使用单线程计划任务
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        absenceStudentAndTeacherOpenIdList.forEach(studentAttendanceVO -> {
            CompletableFuture.runAsync(() -> {
                List<WxMaTemplateData> dataList = new ArrayList<>();
                //通知标题
                WxMaTemplateData data1 = new WxMaTemplateData("thing1", "学生未归寝通知");
                //班级名称
                WxMaTemplateData data2 = new WxMaTemplateData("thing11", studentAttendanceVO.getClassName());
                //学生姓名
                WxMaTemplateData data3 = new WxMaTemplateData("thing12", studentAttendanceVO.getStudentName());
                //原因
                WxMaTemplateData data4 = new WxMaTemplateData("thing13", "未归寝");
                dataList.add(data1);
                dataList.add(data2);
                dataList.add(data3);
                dataList.add(data4);
                asyncConfig.sendWxMessage(studentAttendanceVO.getOpenId(), "EeC_75iP_ZDroTpzdxYdrAuZyH4dhV_JfCGR2MSjPQA", dataList, "pages/office/office");
                //每条消息间隔10秒
                executorService.schedule(() -> {}, 10, TimeUnit.SECONDS);
            });
            //关闭计划任务
            executorService.shutdown();
        });
    }
}
